/**
 * @author hewei
 * @version 1.0
 * @description: 707. 设计链表
 * @date 2022/9/23 14:40
 */

public class MyLinkedList {

    private int length;
    private MyNode dummyHead;
    private MyNode dummyTail;


    public MyLinkedList() {
        length = 0;
        dummyHead = new MyNode();
        dummyTail = new MyNode();
        dummyTail.prev = dummyHead;
        dummyHead.next = dummyTail;
    }

    public int get(int index) {
        if (index + 1 > length) return -1;
        MyNode temp = dummyHead;
        while (index-- >= 0) {
            temp = temp.next;
        }
        return temp.val;
    }

    public void addAtHead(int val) {
        MyNode node = new MyNode(val);
        node.prev = dummyHead;
        node.next = dummyHead.next;
        dummyHead.next = node;
        node.next.prev = node;
        ++length;
    }

    public void addAtTail(int val) {
        MyNode node = new MyNode(val);
        node.next = dummyTail;
        node.prev = dummyTail.prev;
        dummyTail.prev = node;
        node.prev.next = node;
        ++length;
    }

    public void addAtIndex(int index, int val) {
        if (index > length) return;
        MyNode node = new MyNode(val);
        ++length;
        if (index < 0) {
            node.prev = dummyHead;
            node.next = dummyHead.next;
            dummyHead.next = node;
        } else {
            MyNode temp = dummyHead;
            while (index-- > 0) {
                temp = temp.next;
            }
            node.prev = temp;
            node.next = temp.next;
            temp.next = node;
        }
        node.next.prev = node;
    }

    public void deleteAtIndex(int index) {
        if (index + 1 > length) return;
        MyNode temp = dummyHead;
        while (index-- >= 0) {
            temp = temp.next;
        }
        temp.prev.next = temp.next;
        temp.next.prev = temp.prev;
        --length;
    }

    class MyNode {
        MyNode prev;
        MyNode next;
        int val;

        public MyNode() {

        }

        public MyNode(int val) {
            this.val = val;
        }
    }
}
